package com.getbase.tweetme.service;

import java.util.*;

public class CounterService {

    public Map<String, Float> count(List<String> words) {

        Map<String, Integer> m = new TreeMap<>();

        for (String word : words) {
            if (m.containsKey(word)) {
                m.put(word, m.get(word) + 1);
            } else {
                m.put(word, 1);
            }
        }

        return sortByValue(getFrequencies(m, words.size()));
    }

    public Map<String, Float> getFrequencies(Map<String, Integer> m, int totalCount) {
        Map<String, Float> result = new HashMap<>();
        for (String c : m.keySet()) {
            float freq = m.get(c) / (float) totalCount * 100;
            result.put(c, freq);
        }
        return result;
    }

    public TreeMap<String, Float> sortByValue(Map<String, Float> map) {
        ValueComparator vc =  new ValueComparator(map);
        TreeMap<String,Float> sortedMap = new TreeMap<>(vc);
        sortedMap.putAll(map);
        return sortedMap;
    }


    class ValueComparator implements Comparator<String> {

        Map<String, Float> map;

        public ValueComparator(Map<String, Float> base) {
            this.map = base;
        }

        public int compare(String a, String b) {
            if (map.get(a) >= map.get(b)) {
                return -1;
            } else {
                return 1;
            } // returning 0 would merge keys
        }
    }
}
